// SSE实时推送API客户端
class SSEAPI {
    constructor() {
        this.networkSSE = null;
        this.processSSE = null;
        this.isConnected = false;
        this.reconnectDelay = 5000; // 重连延迟（毫秒）
        this.maxReconnectAttempts = 10;
        this.reconnectAttempts = 0;
        this.callbacks = {
            network: [],
            process: [],
            error: [],
            connect: [],
            disconnect: []
        };
    }

    // 启动网络监控SSE - 对应 GET /api/sse
    startNetworkSSE() {
        this.stopNetworkSSE(); // 停止现有连接

        try {
            this.networkSSE = new EventSource('/api/sse');
            
            this.networkSSE.onopen = () => {
                console.log('网络SSE连接已建立');
                this.isConnected = true;
                this.reconnectAttempts = 0;
                this.triggerCallbacks('connect', { type: 'network' });
            };

            this.networkSSE.addEventListener('data', (event) => {
                try {
                    const data = JSON.parse(event.data);
                    this.handleNetworkData(data);
                } catch (error) {
                    console.error('解析网络SSE数据失败:', error);
                    this.triggerCallbacks('error', { error, type: 'network' });
                }
            });

            this.networkSSE.onerror = (error) => {
                console.error('网络SSE连接错误:', error);
                this.isConnected = false;
                this.triggerCallbacks('error', { error, type: 'network' });
                this.handleReconnect('network');
            };

        } catch (error) {
            console.error('启动网络SSE失败:', error);
            this.triggerCallbacks('error', { error, type: 'network' });
        }
    }

    // 启动进程监控SSE - 对应 GET /api/processes/sse
    startProcessSSE() {
        this.stopProcessSSE(); // 停止现有连接

        try {
            this.processSSE = new EventSource('/api/processes/sse');
            
            this.processSSE.onopen = () => {
                console.log('进程SSE连接已建立');
                this.isConnected = true;
                this.reconnectAttempts = 0;
                this.triggerCallbacks('connect', { type: 'process' });
            };

            this.processSSE.addEventListener('processes', (event) => {
                try {
                    const data = JSON.parse(event.data);
                    this.handleProcessData(data);
                } catch (error) {
                    console.error('解析进程SSE数据失败:', error);
                    this.triggerCallbacks('error', { error, type: 'process' });
                }
            });

            this.processSSE.addEventListener('error', (event) => {
                try {
                    const errorData = JSON.parse(event.data);
                    console.error('进程SSE错误:', errorData.error);
                    this.triggerCallbacks('error', { error: errorData.error, type: 'process' });
                } catch (e) {
                    console.error('进程SSE未知错误:', event);
                }
            });

            this.processSSE.onerror = (error) => {
                console.error('进程SSE连接错误:', error);
                this.isConnected = false;
                this.triggerCallbacks('error', { error, type: 'process' });
                this.handleReconnect('process');
            };

        } catch (error) {
            console.error('启动进程SSE失败:', error);
            this.triggerCallbacks('error', { error, type: 'process' });
        }
    }

    // 停止网络SSE
    stopNetworkSSE() {
        if (this.networkSSE) {
            this.networkSSE.close();
            this.networkSSE = null;
            this.triggerCallbacks('disconnect', { type: 'network' });
        }
    }

    // 停止进程SSE
    stopProcessSSE() {
        if (this.processSSE) {
            this.processSSE.close();
            this.processSSE = null;
            this.triggerCallbacks('disconnect', { type: 'process' });
        }
    }

    // 停止所有SSE连接
    stopAll() {
        this.stopNetworkSSE();
        this.stopProcessSSE();
        this.isConnected = false;
    }

    // 处理网络数据
    handleNetworkData(data) {
        // 使用后端提供的格式化字符串
        if (data.interfaces) {
            Object.keys(data.interfaces).forEach(name => {
                const iface = data.interfaces[name];
                // 后端已经提供了格式化字符串，直接使用
                iface.displayReceivedSpeed = iface.received_mbps_text || '0 Mbps';
                iface.displaySentSpeed = iface.sent_mbps_text || '0 Mbps';
                iface.displayTotalReceived = iface.total_received_text || '0 B';
                iface.displayTotalSent = iface.total_sent_text || '0 B';
                iface.displayDropped = iface.dropped_text || '0';
                iface.displayUpdateTime = iface.update_time || '';
            });
        }

        this.triggerCallbacks('network', data);
    }

    // 处理进程数据
    handleProcessData(data) {
        // 使用后端提供的格式化字符串
        if (data.processes) {
            data.processes.forEach(process => {
                process.displayTotalSent = process.total_sent_text || '0 B';
                process.displayTotalRecv = process.total_recv_text || '0 B';
                process.displaySpeedUp = process.speed_up_text || '0 B/s';
                process.displaySpeedDown = process.speed_down_text || '0 B/s';
                process.displayStartTime = process.start_time || 'N/A';
                process.displayLastUpdate = process.last_update || 'N/A';
                
                // 处理连接数据
                if (process.connections) {
                    process.connections.forEach(conn => {
                        conn.displayBytesSent = conn.bytes_sent_text || '0 B';
                        conn.displayBytesRecv = conn.bytes_recv_text || '0 B';
                        conn.displaySpeedUp = conn.speed_up_text || '0 B/s';
                        conn.displaySpeedDown = conn.speed_down_text || '0 B/s';
                        conn.displayCreatedAt = conn.created_at || 'N/A';
                        conn.displayLastSeen = conn.last_seen || 'N/A';
                    });
                }
            });
        }

        // 格式化时间戳
        if (data.timestamp) {
            data.displayTimestamp = data.timestamp; // 后端已返回格式化时间
        }

        this.triggerCallbacks('process', data);
    }

    // 处理重连
    handleReconnect(type) {
        if (this.reconnectAttempts >= this.maxReconnectAttempts) {
            console.error(`${type}SSE达到最大重连次数，停止重连`);
            return;
        }

        this.reconnectAttempts++;
        console.log(`${type}SSE重连中... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);

        setTimeout(() => {
            if (type === 'network') {
                this.startNetworkSSE();
            } else if (type === 'process') {
                this.startProcessSSE();
            }
        }, this.reconnectDelay);
    }

    // 注册回调函数
    on(event, callback) {
        if (this.callbacks[event]) {
            this.callbacks[event].push(callback);
        }
    }

    // 取消注册回调函数
    off(event, callback) {
        if (this.callbacks[event]) {
            const index = this.callbacks[event].indexOf(callback);
            if (index > -1) {
                this.callbacks[event].splice(index, 1);
            }
        }
    }

    // 触发回调函数
    triggerCallbacks(event, data) {
        if (this.callbacks[event]) {
            this.callbacks[event].forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.error(`回调函数执行错误 (${event}):`, error);
                }
            });
        }
    }

    // 获取连接状态
    getConnectionStatus() {
        return {
            isConnected: this.isConnected,
            networkConnected: this.networkSSE && this.networkSSE.readyState === EventSource.OPEN,
            processConnected: this.processSSE && this.processSSE.readyState === EventSource.OPEN,
            reconnectAttempts: this.reconnectAttempts
        };
    }

    // 设置重连参数
    setReconnectConfig(delay, maxAttempts) {
        this.reconnectDelay = delay || 5000;
        this.maxReconnectAttempts = maxAttempts || 10;
    }
}

// 创建全局实例
window.sseAPI = new SSEAPI();